<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习vue</title>
    <script src="../js/vue.js"></script>
    <style>
        *{
            padding: 12px;
        }
    </style>
</head>
<body>
    <div id="root">
        <input type="text" placeholder="输入name过滤" v-model="keyWord">
        <button @click="sortType=1">age升序</button>
        <button @click="sortType=2">age降序</button>
        <button @click="sortType=0">原排序</button>
        <div v-for="p in comShowPersons" :key="p.id">
            {{p.name}} -- {{p.age}}
            <input type="text">
        </div>
    </div>
    <script>
        Vue.config.productionTip = false
        new Vue({
            el:'#root',
            data:{
                sortType:0,
                keyWord:'',
                persons:[
                    {id:'001',name:"f1",age:30},
                    {id:'002',name:"z2",age:20},
                    {id:'003',name:"p3",age:50},
                    {id:'004',name:"ffff1",age:31},
                    {id:'005',name:"fzzzz2",age:21},
                    {id:'006',name:"fzzzzzz3",age:51},
                ],
            },
            //computed写法
            //当watch和computed都能实现的时候，优先使用computed
            computed:{
                comShowPersons(){
                    const arr = this.persons.filter((item) =>{
                            return item.name.indexOf(this.keyWord)!=-1
                        });
                    if(this.sortType){
                        arr.sort((p1,p2)=>{
                            return this.sortType == 1 ? p1.age - p2.age : p2.age - p1.age
                        })
                    }
                    return arr
                }
            },
            methods:{
            },
            //watch写法
            watch:{
                // keyWord(newValue){
                //     this.showPersons = this.persons.filter((item) =>{
                //         return item.name.indexOf(newValue)!=-1
                //     } );
                // }
                //让初识化的时候有值
                keyWord:{
                    immediate:true,
                    handler(newValue){
                        this.showPersons = this.persons.filter((item) =>{
                            return item.name.indexOf(newValue)!=-1
                        } );
                    }
                }
            },
        })
    </script>    
</body>
</html>